package com.shadow.baiqun.delegate.receive.form;

import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.TextView;

import com.rey.material.widget.Spinner;
import com.shadow.baiqun.R;
import com.shadow.baiqun.R2;
import com.shadow.baiqun.config.ItemField;
import com.shadow.baiqun.delegate.common.ResultConverter;
import com.shadow.baiqun.delegate.receive.partcheck.PartCheckEntity;
import com.shadow.baiqun.event.ScanInfoEvent;
import com.shadow.baiqun.global.GlobalDataManager;
import com.shadow.baiqun.global.LocationEntity;
import com.shadow.core.delegate.RxShadowDelegate;
import com.shadow.core.net.callback.IError;
import com.shadow.core.net.callback.ISuccess;
import com.shadow.core.net.rx.RxRestClient;
import com.shadow.ui.progress.sweetalert.DialogLoader;
import com.shadow.ui.progress.sweetalert.IDialogClickListener;
import com.shadow.ui.recycler.MultipleItemEntity;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;


/**
 * @author zy
 * on 2018/7/12
 * 扫描入库表单
 */
public class FormDelegate extends RxShadowDelegate {

    private static final String FORM_DATA = "form";

    public static FormDelegate create(PartCheckEntity checkEntity) {
        final FormDelegate contentDelegate = new FormDelegate();
        final Bundle bundle = new Bundle();
        bundle.putSerializable(FORM_DATA, checkEntity);
        contentDelegate.setArguments(bundle);
        return contentDelegate;
    }

    @BindView(R2.id.toolbar)
    Toolbar mToolbar;
    @BindView(R2.id.et_part_code)
    TextView mTvPartCode;
    @BindView(R2.id.et_bar_code)
    TextView mTvBarCode;
    @BindView(R2.id.et_number)
    TextView mEtNumber;
    @BindView(R2.id.et_label_location)
    TextView mTvLabelLocation;
    @BindView(R2.id.spinner_state)
    Spinner mSpinnerRealLocation;

    private PartCheckEntity mPartCheckEntity;
    private DialogLoader mDialogLoader;
    private String mCurrentDepId;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle bundle = getArguments();
        if (bundle != null) {
            mPartCheckEntity = (PartCheckEntity) bundle.getSerializable(FORM_DATA);
        }
    }

    @Override
    public Object setLayout() {
        return R.layout.delegate_form;
    }

    @Override
    public void onBindView(@Nullable Bundle savedInstanceState, View rootView) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            mToolbar.setNavigationIcon(R.drawable.ic_arrow_back_white_24dp);
            mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    pop();
                }
            });
            mToolbar.setTitle("扫描入库表单");
        }
        if (mPartCheckEntity != null) {
            mTvPartCode.setText(mPartCheckEntity.getPartname());
            mTvBarCode.setText(mPartCheckEntity.getBarCode());
            mEtNumber.setText(String.valueOf(mPartCheckEntity.getStockNum()));
            mTvLabelLocation.setText(mPartCheckEntity.getDepotName());
            initSpinnerData();
        }
        mDialogLoader = new DialogLoader(getContext());
    }

    private void initSpinnerData() {
        List<String> items = new ArrayList<>();
        final List<MultipleItemEntity> locationList = GlobalDataManager.getInstance().getLocationEntityList();
        if (locationList != null && !locationList.isEmpty()) {
            int currentPosition = 0;
            for (int i = 0, size = locationList.size(); i < size; i++) {
                MultipleItemEntity multipleItemEntity = locationList.get(i);
                LocationEntity entity = multipleItemEntity.getField(ItemField.ITEM_OBJ);
                if (entity != null) {
                    if (mPartCheckEntity.getDepotName().equals(entity.getDepotName())) {
                        currentPosition = i;
                        mCurrentDepId = entity.getDepotId();
                    }
                    items.add(entity.getDepotName());
                }
            }
            ArrayAdapter<String> adapter = new ArrayAdapter<>(getContext(), R.layout.row_spn, items);
            adapter.setDropDownViewResource(R.layout.row_spn_dropdown);
            mSpinnerRealLocation.setAdapter(adapter);
            mSpinnerRealLocation.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {
                @Override
                public void onItemSelected(Spinner parent, View view, int position, long id) {
                    MultipleItemEntity multipleItemEntity = locationList.get(position);
                    LocationEntity entity = multipleItemEntity.getField(ItemField.ITEM_OBJ);
                    mCurrentDepId = entity.getDepotId();
                }
            });
            mSpinnerRealLocation.setSelection(currentPosition);
        }
    }

    @Override
    public boolean onBackPressedSupport() {
        pop();
        return false;
    }

    @OnClick(R2.id.tv_save)
    public void onSave() {
        mDialogLoader.showProgressDialog(true, "正在提交", "请稍后...");
        mDisposables.add(RxRestClient.builder()
                .url("WMS/backstage/collectgoods/scanInUpdata")
                .success(new ISuccess() {
                    @Override
                    public void onSuccess(String response) {
                        if (new ResultConverter().isSucceed(response)) {
                            mDialogLoader.stopProgressWithSuccess("提交成功", "保存成功!", new IDialogClickListener() {
                                @Override
                                public void onClick() {
                                    mDialogLoader.clearDialog();
                                    pop();
                                }
                            });
                        } else {
                            mDialogLoader.stopProgressWithSuccess("提交失败", "保存失败!", new IDialogClickListener() {
                                @Override
                                public void onClick() {
                                    mDialogLoader.clearDialog();
                                }
                            });
                        }
                    }
                })
                .error(new IError() {
                    @Override
                    public void onError(int code, String msg) {
                        mDialogLoader.stopProgressWithSuccess("提交失败", "保存失败!", new IDialogClickListener() {
                            @Override
                            public void onClick() {
                                mDialogLoader.clearDialog();

                            }
                        });
                    }
                })
                .params("num", mEtNumber.getText().toString())
                .params("depotid", mCurrentDepId)
                .params("stockid", mPartCheckEntity.getStockId())
                .build()
                .unRestGet());
    }

    @Override
    public void onResume() {
        super.onResume();
        EventBus.getDefault().register(this);
    }

    @Override
    public void onPause() {
        super.onPause();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(priority = 1)
    public void scanEvent(ScanInfoEvent event) {
        //接收了该事件就拦截掉 不会继续往优先级小于priority的地方传递
        EventBus.getDefault().cancelEventDelivery(event);
    }
}
